package com.kmb.business.controller;

import com.kmb.commons.dto.Page;
import com.kmb.commons.dto.Response;
import com.kmb.commons.dto.ResponseResult;
import com.kmb.commons.log.annotation.SysLog;
import com.kmb.provider.api.SfKmUserService;
import com.kmb.provider.domain.SfKmUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户相关.
 * <p>
 * Description:
 * </p>
 *
 * @author Lusifer
 * @version v1.0.0
 * @date 2019-07-26 11:24:44
 * @see com.kmb.business.controller
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping(value = "user")
@Slf4j
public class UserController {

    @Reference(version = "1.0.0")
    private SfKmUserService sfKmUserService;

    /**
     * 获取用户信息
     *
     * @return {@link ResponseResult}
     * PreAuthorize springsecurity注解 有 'user'权限才可以访问
     */
    @PreAuthorize("hasAuthority('user')")
    @SysLog("获取用户信息")
    @GetMapping(value = "/info")
    public ResponseResult<SfKmUser> info() throws Exception {
        // 获取认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return new ResponseResult<SfKmUser>(ResponseResult.CodeStatus.OK, "获取用户信息", null);
    }

    /**
     * 注册
     *
     * @param user {@link SfKmUser}
     * @return {@link ResponseResult}
     */
    @PreAuthorize("hasAuthority('user')")
    @SysLog("用户注册")
    @PostMapping(value = "addUser")
    public ResponseResult<SfKmUser> reg(SfKmUser user) {
        String message = validateReg(user);
        // 通过验证
        if (message == null) {
            int result = sfKmUserService.addUser(user);

            // 注册成功
            if (result > 0) {
                SfKmUser admin = sfKmUserService.getByUsername(user.getUserName());
                return new ResponseResult<SfKmUser>(HttpStatus.OK.value(), "用户注册成功", admin);
            }
        }
        return new ResponseResult<SfKmUser>(HttpStatus.NOT_ACCEPTABLE.value(), message != null ? message : "用户注册失败");
    }

    /**
     * 注册信息验证
     *
     * @param sfKmUser {@link SfKmUser}
     * @return 验证结果
     */
    private String validateReg(SfKmUser sfKmUser) {
        SfKmUser admin = sfKmUserService.getByUsername(sfKmUser.getUserName());

        if (admin != null) {
            return "用户名已存在，请重新输入";
        }

        return null;
    }


    /**
     * 删除
     *
     * @return {@link ResponseResult}
     */
    @PreAuthorize("hasAuthority('user')")
    @PostMapping(value = "deleteUser")
    public ResponseResult<SfKmUser> deleteUser(@RequestParam("userName") String username) {
        int result = sfKmUserService.deleteUser(username);
        return new ResponseResult<SfKmUser>(HttpStatus.NOT_ACCEPTABLE.value(), result != 0 ? "用户删除成功" : "用户删除失败");
    }


    /**
     * 获取用户列表
     *
     * @return {@link ResponseResult}
     */
    @PreAuthorize("hasAuthority('user')")
    @GetMapping(value = "getUserList")
    public ResponseResult getUserList(Page page) {
        List<SfKmUser> list = sfKmUserService.getUserList(page.getPageNo(), page.getPageItems());
        Map<String, Object> result = new HashMap<>();
        result.put("userList", list);
        result.put("page", page);
        return new ResponseResult(ResponseResult.CodeStatus.OK, "获取用户信息列表", result);
    }

    /**
     * 导入用户（固定顺序）
     *
     * @param file
     * @return
     */
    @PostMapping("uploadFile")
    public Response uploadFile(@RequestParam("file") MultipartFile file) {
        // 文件格式转换
        File newFile = null;
        int importNum = 0;
        try {
            newFile = File.createTempFile("tmp", null);
            file.transferTo(newFile);
            importNum = sfKmUserService.importUser(newFile);
            newFile.delete();
        } catch (IOException e) {
            log.error("MultipartFile文件转换File异常", e);
        }
        return Response.ok(importNum);
    }

    /**
     * 修改用户
     *
     * @param userName
     * @param password
     * @return
     */
    @PreAuthorize("hasAuthority('user')")
    @PostMapping("updatePassword")
    public Response updatePassword(SfKmUser user) {
        int i = sfKmUserService.updatePassword(user.getUserPassword(), user.getUserName());
        if (i == 1) {
            return Response.ok();
        } else {
            return Response.error();
        }
    }
}
